package view;

import model.User;
import service.UserService;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import java.awt.*;
import java.util.List;

public class UserManagementPanel extends JPanel {
    private static final Font TITLE_FONT = new Font("微软雅黑", Font.BOLD, 14);
    private static final Font CONTENT_FONT = new Font("微软雅黑", Font.PLAIN, 13);
    private static final Font BUTTON_FONT = new Font("微软雅黑", Font.PLAIN, 13);
    
    private UserService userService;
    private JTable userTable;
    private DefaultTableModel tableModel;
    
    public UserManagementPanel() {
        this.userService = new UserService();
        initComponents();
        loadData();
    }
    
    private void initComponents() {
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createTitledBorder(
            BorderFactory.createEtchedBorder(),
            "用户管理",
            TitledBorder.LEFT,
            TitledBorder.TOP,
            TITLE_FONT
        ));
        
        // 工具栏
        JPanel toolBar = new JPanel(new FlowLayout(FlowLayout.LEFT));
        
        // 搜索框
        JTextField searchField = new JTextField(20);
        searchField.setPreferredSize(new Dimension(200, 25));
        searchField.getDocument().addDocumentListener(new DocumentListener() {
            private void search() {
                String text = searchField.getText().toLowerCase();
                TableRowSorter<DefaultTableModel> sorter = 
                    new TableRowSorter<>(tableModel);
                if (!text.isEmpty()) {
                    sorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
                userTable.setRowSorter(sorter);
            }
            
            @Override
            public void insertUpdate(DocumentEvent e) { search(); }
            @Override
            public void removeUpdate(DocumentEvent e) { search(); }
            @Override
            public void changedUpdate(DocumentEvent e) { search(); }
        });
        toolBar.add(new JLabel("搜索："));
        toolBar.add(searchField);
        
        // 添加按钮
        JButton addButton = new JButton("添加用户");
        addButton.setFont(BUTTON_FONT);
        addButton.setPreferredSize(new Dimension(100, 30));
        addButton.addActionListener(e -> showAddDialog());
        toolBar.add(Box.createHorizontalStrut(20));
        toolBar.add(addButton);
        
        add(toolBar, BorderLayout.NORTH);
        
        // 用户表格
        String[] columnNames = {"ID", "用户名", "角色", "姓名", "状态", "操作"};
        tableModel = new DefaultTableModel(columnNames, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return column == 5; // 只有操作列可编辑
            }
        };
        
        userTable = new JTable(tableModel);
        userTable.setFont(CONTENT_FONT);
        userTable.getTableHeader().setFont(TITLE_FONT);
        userTable.setRowHeight(35);
        userTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        // 设置操作列的渲染器和编辑器
        TableColumn operationColumn = userTable.getColumnModel().getColumn(5);
        operationColumn.setCellRenderer(new view.common.ButtonRenderer());
        operationColumn.setCellEditor(new view.common.ButtonEditor(e -> {
            int row = userTable.getSelectedRow();
            if (row >= 0) {
                int userId = (int) tableModel.getValueAt(row, 0);
                String action = e.getActionCommand();
                
                SwingUtilities.invokeLater(() -> {
                    if ("编辑".equals(action)) {
                        showEditDialog(userId);
                    } else if ("删除".equals(action)) {
                        handleDelete(userId);
                    }
                });
            }
        }));
        
        // 设置列宽
        operationColumn.setPreferredWidth(150);
        operationColumn.setMinWidth(150);
        
        // 设置其他列的宽度
        int[] columnWidths = {60, 100, 80, 100, 80, 150};
        for (int i = 0; i < columnWidths.length; i++) {
            TableColumn column = userTable.getColumnModel().getColumn(i);
            column.setPreferredWidth(columnWidths[i]);
        }
        
        JScrollPane scrollPane = new JScrollPane(userTable);
        scrollPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        add(scrollPane, BorderLayout.CENTER);
    }
    
    private void loadData() {
        tableModel.setRowCount(0);
        List<User> users = userService.getAllUsers();
        for (User user : users) {
            Object[] rowData = {
                user.getId(),
                user.getUsername(),
                user.getRole(),
                user.getName(),
                user.getStatus() == 1 ? "正常" : "禁用",
                "编辑 删除"
            };
            tableModel.addRow(rowData);
        }
    }
    
    private void showAddDialog() {
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), 
            "添加用户", true);
        dialog.setLayout(new BorderLayout());
        
        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        int row = 0;
        
        // 创建输入组件
        JTextField usernameField = new JTextField(20);
        JTextField nameField = new JTextField(20);
        JPasswordField passwordField = new JPasswordField(20);
        JComboBox<String> roleCombo = new JComboBox<>(new String[]{"ADMIN", "TEACHER", "STUDENT"});
        
        // 设置组件大小
        Dimension fieldSize = new Dimension(200, 25);
        usernameField.setPreferredSize(fieldSize);
        nameField.setPreferredSize(fieldSize);
        passwordField.setPreferredSize(fieldSize);
        roleCombo.setPreferredSize(fieldSize);
        
        // 设置字体
        usernameField.setFont(CONTENT_FONT);
        nameField.setFont(CONTENT_FONT);
        passwordField.setFont(CONTENT_FONT);
        roleCombo.setFont(CONTENT_FONT);
        
        // 添加到表单
        addFormField(formPanel, "用户名：", usernameField, gbc, row++);
        addFormField(formPanel, "姓名：", nameField, gbc, row++);
        addFormField(formPanel, "密码：", passwordField, gbc, row++);
        addFormField(formPanel, "角色：", roleCombo, gbc, row++);
        
        // 创建按钮
        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        
        // 设置按钮大小和字体
        Dimension buttonSize = new Dimension(80, 30);
        saveButton.setPreferredSize(buttonSize);
        cancelButton.setPreferredSize(buttonSize);
        saveButton.setFont(BUTTON_FONT);
        cancelButton.setFont(BUTTON_FONT);
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        
        dialog.add(formPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 保存按钮事件
        saveButton.addActionListener(e -> {
            String username = usernameField.getText().trim();
            String name = nameField.getText().trim();
            String password = new String(passwordField.getPassword());
            String role = (String) roleCombo.getSelectedItem();
            
            if (username.isEmpty() || name.isEmpty() || password.isEmpty()) {
                return;
            }
            
            if (userService.addUser(username, password, role, name)) {
                dialog.dispose();
                loadData();
            }
        });
        
        cancelButton.addActionListener(e -> dialog.dispose());
        
        dialog.setMinimumSize(new Dimension(400, 300));
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void handleAction(String action, int row) {
        int id = (int) tableModel.getValueAt(row, 0);
        String username = (String) tableModel.getValueAt(row, 1);
        
        if ("编辑".equals(action)) {
            showEditDialog(id);
        } else if ("删除".equals(action)) {
            if (userService.deleteUser(id)) {
                loadData();
            }
        }
    }
    
    private void showEditDialog(int userId) {
        User user = userService.getUserById(userId);
        if (user == null) return;
        
        JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(this), 
            "编辑用户", true);
        dialog.setLayout(new BorderLayout());
        
        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        int row = 0;
        
        // 创建输入组件
        JTextField usernameField = new JTextField(user.getUsername(), 20);
        JTextField nameField = new JTextField(user.getName(), 20);
        JPasswordField passwordField = new JPasswordField(20);
        JComboBox<String> roleCombo = new JComboBox<>(new String[]{"ADMIN", "TEACHER", "STUDENT"});
        roleCombo.setSelectedItem(user.getRole());
        JComboBox<String> statusCombo = new JComboBox<>(new String[]{"正常", "禁用"});
        statusCombo.setSelectedIndex(user.getStatus() == 1 ? 0 : 1);
        
        // 用户名不可修改
        usernameField.setEnabled(false);
        
        // 设置组件大小和字体
        Dimension fieldSize = new Dimension(200, 25);
        usernameField.setPreferredSize(fieldSize);
        nameField.setPreferredSize(fieldSize);
        passwordField.setPreferredSize(fieldSize);
        roleCombo.setPreferredSize(fieldSize);
        statusCombo.setPreferredSize(fieldSize);
        
        usernameField.setFont(CONTENT_FONT);
        nameField.setFont(CONTENT_FONT);
        passwordField.setFont(CONTENT_FONT);
        roleCombo.setFont(CONTENT_FONT);
        statusCombo.setFont(CONTENT_FONT);
        
        // 添加到表单
        addFormField(formPanel, "用户名：", usernameField, gbc, row++);
        addFormField(formPanel, "姓名：", nameField, gbc, row++);
        addFormField(formPanel, "新密码：", passwordField, gbc, row++);
        addFormField(formPanel, "角色：", roleCombo, gbc, row++);
        addFormField(formPanel, "状态：", statusCombo, gbc, row++);
        
        // 创建按钮
        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        
        // 设置按钮大小和字体
        Dimension buttonSize = new Dimension(80, 30);
        saveButton.setPreferredSize(buttonSize);
        cancelButton.setPreferredSize(buttonSize);
        saveButton.setFont(BUTTON_FONT);
        cancelButton.setFont(BUTTON_FONT);
        
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        
        dialog.add(formPanel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);
        
        // 保存按钮事件
        saveButton.addActionListener(e -> {
            String name = nameField.getText().trim();
            String password = new String(passwordField.getPassword());
            String role = (String) roleCombo.getSelectedItem();
            int status = statusCombo.getSelectedIndex() == 0 ? 1 : 0;
            
            if (name.isEmpty()) {
                JOptionPane.showMessageDialog(dialog, "姓名不能为空！");
                return;
            }
            
            user.setName(name);
            if (!password.isEmpty()) {
                user.setPassword(password);
            }
            user.setRole(role);
            user.setStatus(status);
            
            if (userService.updateUser(user)) {
                dialog.dispose();
                loadData();
                JOptionPane.showMessageDialog(this, "保存成功！");
            } else {
                JOptionPane.showMessageDialog(dialog, 
                    "保存失败！", 
                    "错误", 
                    JOptionPane.ERROR_MESSAGE);
            }
        });
        
        cancelButton.addActionListener(e -> dialog.dispose());
        
        dialog.setMinimumSize(new Dimension(400, 300));
        dialog.pack();
        dialog.setLocationRelativeTo(this);
        dialog.setVisible(true);
    }
    
    private void addFormField(JPanel panel, String label, JComponent field, 
            GridBagConstraints gbc, int row) {
        gbc.gridx = 0;
        gbc.gridy = row;
        gbc.anchor = GridBagConstraints.EAST;
        JLabel jLabel = new JLabel(label);
        jLabel.setFont(CONTENT_FONT);
        panel.add(jLabel, gbc);
        
        gbc.gridx = 1;
        gbc.anchor = GridBagConstraints.WEST;
        panel.add(field, gbc);
    }
    
    private void handleDelete(int userId) {
        // 获取用户信息以显示确认对话框
        User user = userService.getUserById(userId);
        if (user == null) return;
        
        int choice = JOptionPane.showConfirmDialog(
            this,
            "确定要删除用户 '" + user.getUsername() + "' 吗？\n此操作不可恢复！",
            "确认删除",
            JOptionPane.YES_NO_OPTION,
            JOptionPane.WARNING_MESSAGE
        );
        
        if (choice == JOptionPane.YES_OPTION) {
            if (userService.deleteUser(userId)) {
                loadData();  // 重新加载数据
                JOptionPane.showMessageDialog(this, "用户删除成功！");
            } else {
                JOptionPane.showMessageDialog(this, 
                    "删除失败！", 
                    "错误", 
                    JOptionPane.ERROR_MESSAGE);
            }
        }
    }
} 